<template>
	<el-dialog v-model="state.dialogFormVisible" width="60%" :z-index="9" :before-close="cancelHandle">
		<template #header>
			<div class="custom-header">{{ state.isHistoryFlag ? '查看' : state.isUpdateFlag ? '新增' : '编辑' }}</div>
		</template>
		<el-form ref="ruleFormRef" :model="state.form" :rules="rules">
			<el-row>
				<el-col :span="16">
					<el-form-item prop="reportingUnit" label="填报单位" label-width="120px">
						<el-input v-model="state.form.reportingUnit" :disabled="state.isHistoryFlag" />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item prop="reportingDate" label="填报日期" label-width="120px">
						<el-date-picker
							v-model="state.form.reportingDate"
							type="date"
							format="YYYY-MM-DD"
							value-format="YYYY-MM-DD"
							:disabled="state.isHistoryFlag"
						/>
					</el-form-item>
				</el-col>

				<el-col :span="8">
					<el-form-item prop="reportingLink" label="填报人" label-width="120px">
						<el-input v-model="state.form.reportingLink" :disabled="state.isHistoryFlag" />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item prop="linkTel" label="联系电话" label-width="120px">
						<el-input v-model="state.form.linkTel" :disabled="state.isHistoryFlag" />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item prop="linkEmail" label="联系人邮箱" label-width="120px">
						<el-input v-model="state.form.linkEmail" :disabled="state.isHistoryFlag" />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item prop="groupStandardName" label="团体标准名称" label-width="120px">
						<el-input v-model="state.form.groupStandardName" :disabled="state.isHistoryFlag" />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item prop="groupStandardNumber" label="团体标准编号" label-width="120px">
						<el-input v-model="state.form.groupStandardNumber" :disabled="state.isHistoryFlag" />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item prop="issuedUnit" label="发布单位" label-width="120px">
						<el-input v-model="state.form.issuedUnit" :disabled="state.isHistoryFlag" />
					</el-form-item>
				</el-col>

				<el-col :span="8">
					<el-form-item prop="releaseDate" label="发布日期" label-width="120px">
						<el-date-picker
							v-model="state.form.releaseDate"
							type="date"
							format="YYYY-MM-DD"
							value-format="YYYY-MM-DD"
							:disabled="state.isHistoryFlag"
						/>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item prop="implementationDate" label="实施日期" label-width="120px">
						<el-date-picker
							v-model="state.form.implementationDate"
							type="date"
							format="YYYY-MM-DD"
							value-format="YYYY-MM-DD"
							:disabled="state.isHistoryFlag"
						/>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item prop="firstEditorUnit" label="第一主编单位" label-width="120px">
						<el-input v-model="state.form.firstEditorUnit" autocomplete="off" :disabled="state.isHistoryFlag" />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item prop="secondEditorUnit" label="第二主编单位" label-width="120px">
						<el-input v-model="state.form.secondEditorUnit" autocomplete="off" :disabled="state.isHistoryFlag" />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item prop="thirdEditorUnit" label="第三主编单位" label-width="120px">
						<el-input v-model="state.form.thirdEditorUnit" autocomplete="off" :disabled="state.isHistoryFlag" />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item prop="fourthEditorUnit" label="第四主编单位" label-width="120px">
						<el-input v-model="state.form.fourthEditorUnit" autocomplete="off" :disabled="state.isHistoryFlag" />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item prop="standardType" label="类型" label-width="120px">
						<el-select v-model="state.form.standardType" placeholder="请选择" :disabled="state.isHistoryFlag">
							<el-option v-for="item in leibielist" :key="item.code" :label="item.name" :value="item.code"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="16">
					<el-form-item prop="participatingUnits" label="参编单位：(多个单位逗号隔开)" label-width="210px">
						<el-input v-model="state.form.participatingUnits" :disabled="state.isHistoryFlag" />
					</el-form-item>
				</el-col>
			</el-row>

			<el-row class="" style="margin-left: 120px">
				<el-col :span="8"> 在全国团体标准信息平台公开 </el-col>
				<el-col :span="8">
					<el-radio-group v-model="state.form.openPlatform" class="ml-4" :disabled="state.isHistoryFlag">
						<el-radio :value="1">已公开</el-radio>
						<el-radio :value="0">未公开</el-radio>
					</el-radio-group>
				</el-col>
				<el-col :span="8">
					<el-input v-model="state.form.openPlatformRemark" autocomplete="off" :disabled="state.isHistoryFlag" />
				</el-col>
			</el-row>

			<el-row style="margin-left: 120px; margin-top: 15px; margin-bottom: 15px">
				<el-col :span="8"> 在全国工程建设标准化信息网公开 </el-col>
				<el-col :span="8">
					<el-radio-group v-model="state.form.publicizedNetwork" class="ml-4" :disabled="state.isHistoryFlag">
						<el-radio :value="1">已公开</el-radio>
						<el-radio :value="0">未公开</el-radio>
					</el-radio-group>
				</el-col>
				<el-col :span="8">
					<el-input v-model="state.form.publicizedNetworkRemark" autocomplete="off" :disabled="state.isHistoryFlag" />
				</el-col>
			</el-row>

			<el-row style="margin-left: 120px">
				<el-col :span="8"> 在其他网站公开 </el-col>
				<el-col :span="8">
					<el-radio-group v-model="state.form.publicWebsites" class="ml-4" :disabled="state.isHistoryFlag">
						<el-radio :value="1">已公开</el-radio>
						<el-radio :value="0">未公开</el-radio>
					</el-radio-group>
				</el-col>
				<el-col :span="8">
					<el-input v-model="state.form.publicWebsitesRemark" autocomplete="off" :disabled="state.isHistoryFlag" />
				</el-col>
			</el-row>

			<el-form-item label="单位组织表" label-width="120px">
				<el-table ref="multipleTableRef" :data="state.form.units" style="width: 100%" @selection-change="handleSelectionChange">
					<el-table-column type="selection" width="55" />
					<el-table-column label="自我声明公开执行的成员组织(单位)">
						<template #default="scope">
							<el-input v-model="scope.row.orgName" :disabled="state.isHistoryFlag"></el-input>
						</template>
					</el-table-column>
					<el-table-column property="orgCode" label="组织机构代码">
						<template #default="scope">
							<el-input v-model="scope.row.orgCode" :disabled="state.isHistoryFlag"></el-input>
						</template>
					</el-table-column>
					<el-table-column property="location" label="注册所在地">
						<template #default="scope">
							<el-input v-model="scope.row.location" :disabled="state.isHistoryFlag"></el-input>
						</template>
					</el-table-column>
					<el-table-column property="legalPerson" label="法定代表人或授权代表人">
						<template #default="scope">
							<el-input v-model="scope.row.legalPerson" :disabled="state.isHistoryFlag"></el-input>
						</template>
					</el-table-column>
					<el-table-column property="phoneNumber" label="手机号">
						<template #default="scope">
							<el-input v-model="scope.row.phoneNumber" :disabled="state.isHistoryFlag"></el-input>
						</template>
					</el-table-column>
					<el-table-column property="emailAddress" label="电子邮件">
						<template #default="scope">
							<el-input v-model="scope.row.emailAddress" :disabled="state.isHistoryFlag"></el-input>
						</template>
					</el-table-column>
				</el-table>
				<div style="display: flex">
					<el-button type="primary" :disabled="state.isHistoryFlag" @click="addDanwei">
						<el-icon><Plus /></el-icon>
					</el-button>

					<el-button type="danger" :disabled="state.isHistoryFlag" @click="reduceDanwei">
						<el-icon><Minus /></el-icon>
					</el-button>
				</div>
			</el-form-item>

			<el-form-item label="" label-width="120px">
				<div>标准全文发布版上传(请上传word或Pdf)</div>
				<div style="width: 60%">
					<el-upload
						ref="uploadRef"
						:action="uploadApi"
						:headers="uploadHeaders"
						:data="uploadData"
						accept=".pdf, .doc, .docx"
						:limit="1"
						:file-list="uploadShowList"
						:on-exceed="handleExceed"
						:on-preview="handleUploadFilePreview"
						:on-success="handleUploadFileSuccess"
						:on-error="handleUploadFileError"
						:on-remove="handleUploadfileRemove"
						:disabled="state.isHistoryFlag"
					>
						<el-button type="primary" :disabled="state.isHistoryFlag">上传</el-button>
						<!-- <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div> -->
					</el-upload>
				</div>
			</el-form-item>

			<!-- <el-form-item v-if="state.isAuditUpdate" label="" label-width="120px">
				<el-radio-group v-model="state.form.applyStatus">
					<el-radio v-for="item in state.statusList" :key="item.value" :value="item.value">
						{{ item.label }}
					</el-radio>
				</el-radio-group>
			</el-form-item> -->

			<el-form-item v-if="state.isHistoryFlag" label="历史修改意见" label-width="120px">
				<el-table :data="state.historyyijian" style="width: 100%">
					<el-table-column prop="approvalOpinion" label="历史意见" header-align="center" align="center" />
					<el-table-column prop="reviewer" label="审批人" header-align="center" align="center" />
					<el-table-column prop="approvalDate" label="日期" header-align="center" align="center" />
				</el-table>
			</el-form-item>

			<el-form-item label="" label-width="120px">
				<div>用户承诺</div>
				<div>本企业自愿注册成为上海市工程建设标准信息系统的注册企业，并作出如下承诺：</div>
				<div>一、本企业所提交的内容及其材料真实有效，并对信息真实性承担法律责任；</div>
				<div>二、不利用平台发表色情低俗、暴力血腥、造谣散播等各类法律法规及相关政策规定的评议或意见；</div>
			</el-form-item>
		</el-form>

		<template #footer>
			<span class="dialog-footer">
				<el-button v-if="!state.isHistoryFlag" @click="sumbitHandle(ruleFormRef, false)">暂存</el-button>
				<el-button v-if="!state.isHistoryFlag" type="primary" @click="sumbitHandle(ruleFormRef, true)">提交</el-button>
				<el-button type="info" @click="cancelHandle"> 关闭 </el-button>
			</span>
		</template>
	</el-dialog>
</template>
<script lang="ts" setup>
import { UploadFile } from '@/interface/declare'
import type { FormInstance, FormRules, UploadProps, UploadRawFile } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { reactive, ref } from 'vue'

import { useDictionaryStore } from '@/store/modules/dictionary'
import { generateUUID } from '@/utils/tool'
const dictionaryStore = useDictionaryStore()
const leibielist = dictionaryStore.getDictionaryByCode('T003')

import { groupStandardAddApi, groupStandardDetailApi, groupStandardStatusApi } from '@/api/group/index'
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()

import { filePreviewByName } from '@/api/sys/upload'

interface RuleForm {
	reportingUnit: String
	reportingDate: String
	reportingLink: String
	linkTel: String
	linkEmail: String
	groupStandardName: String
	groupStandardNumber: String
	issuedUnit: String
	releaseDate: String
	implementationDate: String
	firstEditorUnit: String
	standardType: String
}
const state = reactive({
	form: {
		reportingUnit: '',
		reportingDate: '',
		reportingLink: '',
		standardType: '',
		linkTel: '',
		linkEmail: '',
		groupStandardName: '',
		groupStandardNumber: '',
		issuedUnit: '',
		releaseDate: '',
		implementationDate: '',
		firstEditorUnit: '',
		secondEditorUnit: '',
		thirdEditorUnit: '',
		fourthEditorUnit: '',
		participatingUnits: '', // 多的时候逗号隔开
		openPlatform: '',
		openPlatformRemark: '',
		publicizedNetwork: '',
		publicizedNetworkRemark: '',
		publicWebsites: '',
		publicWebsitesRemark: '',
		units: [],
		hasSubmit: false
	},
	dialogFormVisible: false,
	isUpdateFlag: false,
	checkedList: [],
	// 审核画面需要的
	isShowView: false,
	isAuditUpdate: false,
	statusList: [],
	isHistoryFlag: false,
	historyyijian: []
})
const mobileRegExp = /^1[3456789]\d{9}$/
const telValidator = (rule, value, callback) => {
	if (mobileRegExp.test(value)) {
		callback()
	} else {
		callback(new Error('手机号格式不正确'))
	}
}
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<RuleForm>>({
	reportingUnit: [{ required: true, message: '请输入填报单位', trigger: 'blur' }],
	reportingDate: [{ required: true, message: '请选择填报日期', trigger: ['blur', 'change'] }],
	reportingLink: { required: true, message: '请输入填报人', trigger: ['blur', 'change'] },
	linkTel: [
		{ required: true, message: '请输入填报电话', trigger: ['blur', 'change'] },
		{ validator: telValidator, trigger: ['blur', 'change'] }
	],
	linkEmail: { type: 'email', required: true, message: '请输入填报邮箱', trigger: ['blur', 'change'] },
	groupStandardName: { required: true, message: '请输入团体标准名称', trigger: ['blur', 'change'] },
	groupStandardNumber: { required: true, message: '请输入团体标准编号', trigger: ['blur', 'change'] },
	issuedUnit: { required: true, message: '请输入发布单位', trigger: ['blur', 'change'] },
	releaseDate: { required: true, message: '请输入发布日期', trigger: ['blur', 'change'] },
	implementationDate: { required: true, message: '请输入实施日期', trigger: ['blur', 'change'] },
	firstEditorUnit: { required: true, message: '请输入第一主编单位', trigger: ['blur', 'change'] },
	standardType: { required: true, message: '请选择类别', trigger: ['change'] }
})
const emit = defineEmits(['refreshDataList'])
// 附件上传
const uploadApi = `${import.meta.env.MODE === 'development' ? 'http://220.196.89.86:9173' : window.location.protocol + '//' + window.location.host}/JGBStandardWebApi/api/files/upload`
const uploadHeaders = {
	Authorization: userStore.token
}
const uploadData = {
	extCode: 'other',
	remark: '附件'
}
const uploadRef = ref()
const uploadList = ref<UploadFile[]>([])
const uploadShowList = ref<UploadRawFile[]>([])
const handleExceed: UploadProps['onExceed'] = files => {
	ElMessageBox.confirm('只能上传一份文件，若要替换，请先删除已有文件', '温馨提示', {
		showConfirmButton: false,
		cancelButtonText: '知道了',
		type: 'warning'
	})
}

const handleUploadFilePreview = (ruploadFile: any) => {
	if (ruploadFile.systemFileName) {
		filePreviewByName(ruploadFile.systemFileName).then(res => {
			window.open(res.data.url)
		})
	} else {
		filePreviewByName(ruploadFile?.response.data.systemFileName).then(res => {
			window.open(res.data.url)
		})
	}
}

const handleUploadFileSuccess = (res: any, uploadFile: UploadRawFile) => {
	if (res.code == '200') {
		uploadList.value = []
		uploadList.value.push(res.data)
	} else {
		handleUploadFileError(res, uploadFile)
	}
}

const handleUploadfileRemove = (file: UploadRawFile) => {
	uploadList.value = []
}

const handleUploadFileError = (error: Error, uploadFile: UploadRawFile) => {
	ElMessage.error(error.message)
	uploadShowList.value = uploadShowList.value.filter((item: UploadRawFile) => item.uid !== uploadFile.uid)
}
// ==============================================================
const init = (isUpdate: Boolean, row: any, isChakan: Boolean) => {
	state.isUpdateFlag = isUpdate
	if (isChakan) {
		state.isHistoryFlag = true
	} else {
		state.isHistoryFlag = false
	}
	state.isAuditUpdate = false
	if (!isUpdate) {
		detailMethods(row.id)
	}
	state.dialogFormVisible = true
}
// 审核发布新增-查看
const initSh = (isUpdate: Boolean, row: any, isShow: Boolean) => {
	statusListApi()
	if (isShow) {
		state.form['approvalopinion'] = {
			approvalOpinion: '',
			reviewer: '',
			approvalDate: ''
		}
		state.isShowView = true
		state.isHistoryFlag = true
		state.isAuditUpdate = false
		state.historyyijian = []
		console.log('查看')
	} else {
		state.form['applyStatus'] = ''
		state.isAuditUpdate = true
		state.isHistoryFlag = false
		state.historyyijian = []
		state.isShowView = false
		console.log('编辑、新增')
	}
	state.isUpdateFlag = isUpdate
	if (!isUpdate) {
		detailMethods(row.id)
	}
	state.dialogFormVisible = true
}
// 请求参数列表参数错误问题 录入采集
const delzd = () => {
	delete state.form['applyStatus']
	delete state.form['applyStatusValue']
	delete state.form['publishStatus']
	delete state.form['publishStatusValue']
	delete state.form['approvalOpinion']
	delete state.form['releasedStandardFile']
}
const delShenheAdd = () => {
	delete state.form['approvalOpinion']
	delete state.form['publishStatus']
	delete state.form['publishStatusValue']
	delete state.form['applyStatusValue']
	delete state.form['releasedStandardFile']
}
const fileShow = (row: any) => {
	var file = {}
	if (row.releasedStandardFile) {
		Object.assign(file, row.releasedStandardFile)
		file['name'] = row.releasedStandardFile['fileName']
		uploadShowList.value.push(file)
		uploadList.value.push(file)
	}
}
// 详情接口
const detailMethods = async (id: Number | String) => {
	var params = {
		id: id
	}
	await groupStandardDetailApi(params).then(res => {
		// console.log("详情", res)
		Object.assign(state.form, res.data)
		fileShow(res.data)
		if (state.isHistoryFlag) {
			state.historyyijian.push(res.data.approvalOpinion)
		}
	})
}
const sumbitHandle = async (formEl: FormInstance | undefined, isFlag: Boolean) => {
	// console.log(state.isAuditUpdate)
	if (!formEl) {
		return
	}
	await formEl.validate((valid, fields) => {
		if (valid) {
			if (!state.isAuditUpdate) {
				delzd()
			} else {
				delShenheAdd()
			}
			if (uploadList.value.length > 0) {
				state.form['releasedStandardFileId'] = uploadList.value[0]['id']
			}
			state.form.reportingDate = state.form.reportingDate ? state.form.reportingDate + ' 00:00:00' : ''
			state.form.releaseDate = state.form.releaseDate ? state.form.releaseDate + ' 00:00:00' : ''
			state.form.implementationDate = state.form.implementationDate ? state.form.implementationDate + ' 00:00:00' : ''
			// console.log("最后提交的数据：", state.form)
			if (isFlag) {
				// 判断是暂存还是提交
				submitRecord()
			} else {
				zancun()
			}
		} else {
			console.log('提交错误', fields)
		}
	})
}
const zancun = async () => {
	state.form['hasSubmit'] = false
	// console.log("暂存数据", state.form)
	await groupStandardAddApi(state.form).then(res => {
		ElMessage.success({
			message: '操作成功',
			duration: 500
		})
		cancelHandle()
	})
}
const submitRecord = async () => {
	state.form['hasSubmit'] = true
	// console.log("提交数据", state.form)
	await groupStandardAddApi(state.form).then(res => {
		ElMessage.success({
			message: '操作成功',
			duration: 500
		})
		cancelHandle()
	})
}

const resetForm = () => {
	var lsform = {
		reportingUnit: '',
		reportingDate: '',
		reportingLink: '',
		standardType: '',
		linkTel: '',
		linkEmail: '',
		groupStandardName: '',
		groupStandardNumber: '',
		issuedUnit: '',
		releaseDate: '',
		implementationDate: '',
		firstEditorUnit: '',
		secondEditorUnit: '',
		thirdEditorUnit: '',
		fourthEditorUnit: '',
		participatingUnits: '', // 多的时候逗号隔开
		openPlatform: '',
		openPlatformRemark: '',
		publicizedNetwork: '',
		publicizedNetworkRemark: '',
		publicWebsites: '',
		publicWebsitesRemark: '',
		units: [],
		hasSubmit: false
	}
	state.form = { ...lsform }
}

const cancelHandle = () => {
	ruleFormRef.value?.resetFields() // 表单验证关闭
	resetForm()
	state.isHistoryFlag = false
	state.historyyijian = []
	state.checkedList = []
	state.dialogFormVisible = false
	// 文件清空
	uploadList.value = []
	uploadShowList.value = []
	emit('refreshDataList')
}

// 单位组织表格 操作
const handleSelectionChange = val => {
	console.log('选择的数据：', val)
	state.checkedList = val
}
const addDanwei = () => {
	state.form.units.push({
		id: generateUUID(), // 唯一id
		orgName: '',
		orgCode: '',
		location: '',
		legalPerson: '',
		phoneNumber: '',
		emailAddress: ''
	})
}
const reduceDanwei = () => {
	if (state.checkedList.length == 0) {
		ElMessage.warning('请选择数据')
		return
	}
	var newCheckedList = [...state.checkedList]
	var oldUnits = [...state.form.units]
	var newUnits = []
	if (state.checkedList && state.checkedList.length > 0) {
		newUnits = oldUnits.filter(a => !newCheckedList.some(b => a.id === b.id))
		// console.log(newUnits)
		state.form.units = newUnits
		state.checkedList = []
	}
}
// 状态类别
const statusListApi = async () => {
	await groupStandardStatusApi().then(res => {
		state.statusList = res.data
	})
	// 只要通过的filter
	var newStatusList = [...state.statusList]
	state.statusList = newStatusList.filter(item => item.label.includes('通过'))
	// console.log(state.statusList)
}
defineExpose({
	init,
	initSh
})
</script>

<style scoped>
.dialog-footer {
	padding-bottom: 20px;
}
</style>
